<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('/excel')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100px;height:100px">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" prop="" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="doDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 30]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <empDialog ref="emDialog" @success="hSuccess" @close="showDialog=false" />
      </el-dialog>
      <!-- 添加分配角色弹框 -->
      <el-dialog title="添加角色" :visible.sync="showDialogRole">
        <AssignRole :role-id="roleId" @close="showDialogRole=false" />
      </el-dialog>

    </div>
  </div>
</template>
<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import AssignRole from './assignRole.vue'
import empEmployees from '@/constant/employees'
import empDialog from './empDialog.vue'
console.log(empEmployees.hireType)
const hireType = empEmployees.hireType.reduce((ecc, item) => {
  ecc[item.id] = item.value
  return ecc
}, {})
export default {
  components: {
    empDialog,
    AssignRole

  },
  data() {
    return {
      roleId: '', // 接收分配角色传过去的id
      showDialogRole: false, // 控制分配角色弹层显示
      showDialog: false, // 添加弹层的显示
      list: [],
      page: 1,
      size: 2,
      total: 0

    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 获取当前用户传id给子组件
    hAssignRole(id) {
      this.roleId = id
      this.showDialogRole = true
    },
    // 实现excel文件的导出
    dataFormat(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1. 获取表头
      const one = list[0]
      let headers = []
      if (one) {
        headers = Object.keys(one).map(enkey => {
          return mapInfo[enkey]
        })
      }
      // 2. 将每一个对象对象中的值存到一个数组中 ，将每个数组存储到大数组中
      const data = list.map(item => {
        return Object.values(item)
      })
      return { headers, data }
    },
    async handleDownload() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log('获取用户信息', res)
        // this.list = res.data.rows
        const { headers, data } = this.dataFormat(res.data.rows)
        //  import('@/vendor/Export2Excel')  懒加载的方式读取一个文件（模块）返回是一个promise实例对象
        import('@/vendor/Export2Excel').then(excel => {
        // excel指的是模块对象(文件对象)，就可以直接调用文件中的任何函数或者使用文件中的任何变量  excel.函数名()   || excel.变量
          console.log(excel, 'excel')
          //  excel调用export_json_to_excel()
          excel.export_json_to_excel({
            header: headers,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 根据ID删除数据
    doDel(id) {
      this.$confirm('您确定删除嘛？').then(
        async() => {
          const res = await delEmployee(id)
          console.log('delEmployee', res)
          // 处理特殊情况 当页面只有一条数据的时候 就让page减一
          if (this.page.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          // 重新渲染页面
          this.loadEmployeeList()
        }).catch(err => err)
    },
    // 重置表单
    hClose() {
      this.$refs.emDialog.resetform()
    },
    hSuccess() {
      this.total++
      const Maxpage = Math.ceil(this.total / this.size)// 求最大页面
      this.page = Maxpage
      // 关闭
      this.showDialog = false
      // 重新渲染数据
      this.loadEmployeeList()
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeeList()
    },
    // 修改聘用形式
    formatEmployment(id) {
      return hireType[id] || '未知'
    },

    // 获取页面列表
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log('获取用户信息', res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }

  }
}
</script>
